//
//  ImagePicker.m
//  米哈时代
//
//  Created by abc123 on 2025/9/18.
//

#import "ImagePicker.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import "JsbBridgeTest.h"

@implementation ImagePicker

+ (instancetype)sharedInstance {
    static ImagePicker *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[ImagePicker alloc] init];
    });
    return sharedInstance;
}

// 调用系统相册
- (void)pickImageFromGallery {
    dispatch_async(dispatch_get_main_queue(), ^{
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        //imagePicker.mediaTypes = @[(NSString *)kUTTypeImage];
        imagePicker.mediaTypes = @[(NSString *)@"public.image"];
        imagePicker.delegate = self;
        imagePicker.allowsEditing = NO;
        
        // 获取当前显示的ViewController
        UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
        [rootViewController presentViewController:imagePicker animated:YES completion:nil];
    });
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey, id> *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    if (image) {
        [self handleImagePickerResultWithImage:image];
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
    // 可以发送取消事件到JS
    //[NativeBridge sendToJs:@"selectFileCancel" jsonObject:@{}];
    [JsbBridgeTest sendToJs:@"selectFileReturn" data:@"0"];
}

#pragma mark - 处理图片

- (void)handleImagePickerResultWithImage:(UIImage *)image {
    // 1. 获取Cocos可写目录
    NSString *cocosWritablePath = [self getCocosWritablePath];
    
    // 2. 生成目标文件名
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyyMMdd_HHmmss"];
    NSString *timeStamp = [formatter stringFromDate:[NSDate date]];
    NSString *destFileName = [NSString stringWithFormat:@"IMG_%@.jpg", timeStamp];
    
    // 3. 保存图片到目标路径
    NSString *fullPath = [cocosWritablePath stringByAppendingPathComponent:destFileName];
    NSData *imageData = UIImageJPEGRepresentation(image, 0.9); // 90%质量
    BOOL success = [imageData writeToFile:fullPath atomically:YES];
    
    if (success) {
        // 4. 准备返回给JS的数据
        NSDictionary *jsonObject = @{
            @"fileName": destFileName,
            @"fullPath": fullPath,
            @"source": fullPath // iOS中直接使用保存后的路径
        };
        NSLog(@"成功:%@", fullPath);
        // 5. 发送到JS
        [JsbBridgeTest sendToJs:@"selectFileReturn" data:jsonObject];
    } else {
        // 发送错误事件到JS
        //[JsbBridgeTest sendToJs:@"selectFileError" jsonObject:@{@"error": @"Failed to save image"}];
        [JsbBridgeTest sendToJs:@"errAlert" data:@"选取失败！"];
    }
}

- (NSString *)getCocosWritablePath {
    // 获取Documents目录
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    
    // Cocos通常使用"Game"作为子目录，根据实际情况调整
    NSString *cocosPath = [documentsDirectory stringByAppendingPathComponent:@"Game"];
    
    // 确保目录存在
    NSFileManager *fileManager = [NSFileManager defaultManager];
    [fileManager createDirectoryAtPath:cocosPath withIntermediateDirectories:YES attributes:nil error:nil];
    
    return cocosPath;
}

@end
